<template>
  <div>
    <div class="registertip">注册</div>
    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field v-model="username" name="用户名" label="用户名" placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名' }]" />
        <van-field v-model="password" type="password" name="密码" label="密码" placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]" />
        <van-field v-model="phone" label="手机号" placeholder="请输入手机号"/>
      </van-cell-group>
      <div style="margin: 16px;">
        <van-button round block type="primary" native-type="submit" color="#ff5777">
          注册
        </van-button>
      </div>
    </van-form>
    <div style="margin: 16px; font-size: 14rem">
      <router-link to="/login" style="color: #999;">已有账号？去登录</router-link>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { Toast } from 'vant';
import { useRouter } from 'vue-router';

const router = useRouter();
const username = ref('');
const password = ref('');
const phone = ref('');

const users = ref(JSON.parse(localStorage.getItem("users")) || []);

// 注册处理函数
const onSubmit = () => {
  if (!username.value || !password.value || !phone.value) {
    Toast('请填写用户名、密码和手机号');
    return;
  }
  const existingUser = users.value.find(user => user.username === username.value);
  if (existingUser) {
    Toast('用户名已存在');
    return;
  }
  // 将手机号加入用户对象
  users.value.push({ username: username.value, password: password.value, phone: phone.value });
  localStorage.setItem("users", JSON.stringify(users.value));
  Toast('注册成功，请登录');
  router.push({ path: '/mine' });
};
</script>

<style scoped>
.registertip {
  width: 100%;
  height: 44rem;
  text-align: center;
  margin: 0 0 15rem 0;
  font-size: 20rem;
  line-height: 44rem;
  border-bottom: 1rem solid #d1cdcd;
  color: #999;
}
</style>
